﻿#if NETFX || NETCORE

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Apewer.Surface
{

    /// <summary></summary>
    internal class BlockList : ListBox
    {
        private List<Color> _color = new List<Color>();

        /// <summary></summary>
        public BlockList()
        {
            Font = FormsUtility.DefaultFont;
            BorderStyle = BorderStyle.None;
            DrawMode = DrawMode.OwnerDrawVariable;
            SelectionMode = SelectionMode.One;

            MeasureItem += Event_MeasureItem;
            DrawItem += Event_DrawItem;
        }

        /// <summary></summary>
        private void Event_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (_color.Count > 0)
            {
                RectangleF vrf = new RectangleF(8, e.Bounds.Top + 4, e.Bounds.Width - 16, 16);
                Brush vb = new SolidBrush(GetColor(e.Index));
                string vs = Items[e.Index].ToString();
                e.DrawBackground();
                e.DrawFocusRectangle();
                e.Graphics.DrawString(vs, e.Font, vb, vrf);
            }
        }

        /// <summary></summary>
        private void Event_MeasureItem(object sender, MeasureItemEventArgs e)
        {
            e.ItemHeight = 25;
        }

        /// <summary></summary>
        private Color GetColor(int index)
        {
            if (index >= _color.Count) return ForeColor;
            return _color[index];
        }

        /// <summary></summary>
        public void Append(string text) => Write(text, ForeColor);

        /// <summary></summary>
        public void Write(string text) => Write(text, ForeColor);

        /// <summary></summary>
        public void Black(string text) => Write(text, FormsUtility.Black);

        /// <summary></summary>
        public void Green(string text) => Write(text, FormsUtility.Green);

        /// <summary></summary>
        public void Red(string text) => Write(text, FormsUtility.Red);

        /// <summary></summary>
        public void Gray(string text) => Write(text, FormsUtility.GraceLocked);

        /// <summary></summary>
        public void Error(string text) => Red(text);

        /// <summary></summary>
        public void Write(string text, Color color)
        {
            var t = string.IsNullOrEmpty(text) ? "" : text.Trim();
            while (_color.Count < Items.Count)
            {
                _color.Add(ForeColor);
            }
            while (_color.Count > Items.Count)
            {
                _color.RemoveAt(_color.Count - 1);
            }
            _color.Add((color == null) ? FormsUtility.Black : color);
            Items.Add(t);
        }

        /// <summary></summary>
        public void SelectLast()
        {
            if (Items.Count > 0) SelectedIndex = Items.Count - 1;
        }

    }
}

#endif
